/**
 * 字段级权限控制模块
 * 实现基于角色的字段访问控制
 */

// 用户角色定义
const USER_ROLES = {
  ADMIN: 'admin',        // 系统管理员
  DIRECTOR: 'director',  // 董事长
  MANAGER: 'manager',    // 研发经理
  ENGINEER: 'engineer',  // 工程师
  BUSINESS: 'business',  // 业务人员
  REGULAR: 'regular'     // 普通用户
};

/**
 * 字段权限策略
 * 定义每个角色对应的字段访问权限
 * 
 * 权限类型：
 * - read: 只读权限
 * - write: 读写权限
 * - none: 无权限
 * 
 * 全局默认：如无特殊定义，字段默认为所有角色可读，只有admin、director、manager可写
 */
const FIELD_ACCESS_POLICY = {
  // 基础信息字段
  model: {
    [USER_ROLES.ADMIN]: 'write',
    [USER_ROLES.DIRECTOR]: 'write',
    [USER_ROLES.MANAGER]: 'write',
    [USER_ROLES.ENGINEER]: 'read',
    [USER_ROLES.BUSINESS]: 'read',
    [USER_ROLES.REGULAR]: 'read'
  },
  projectType: {
    [USER_ROLES.ADMIN]: 'write',
    [USER_ROLES.DIRECTOR]: 'write',
    [USER_ROLES.MANAGER]: 'write',
    [USER_ROLES.ENGINEER]: 'read',
    [USER_ROLES.BUSINESS]: 'read',
    [USER_ROLES.REGULAR]: 'read'
  },
  customerName: {
    [USER_ROLES.ADMIN]: 'write',
    [USER_ROLES.DIRECTOR]: 'write',
    [USER_ROLES.MANAGER]: 'write', 
    [USER_ROLES.ENGINEER]: 'read',
    [USER_ROLES.BUSINESS]: 'write', // 业务人员需要修改客户信息
    [USER_ROLES.REGULAR]: 'read'
  },
  
  // 状态和进度字段
  level1: {
    [USER_ROLES.ADMIN]: 'write',
    [USER_ROLES.DIRECTOR]: 'write',
    [USER_ROLES.MANAGER]: 'write',
    [USER_ROLES.ENGINEER]: 'read',
    [USER_ROLES.BUSINESS]: 'read',
    [USER_ROLES.REGULAR]: 'read'
  },
  level2: {
    [USER_ROLES.ADMIN]: 'write',
    [USER_ROLES.DIRECTOR]: 'write',
    [USER_ROLES.MANAGER]: 'write',
    [USER_ROLES.ENGINEER]: 'read',
    [USER_ROLES.BUSINESS]: 'read',
    [USER_ROLES.REGULAR]: 'read'
  },
  completionPercentage: {
    [USER_ROLES.ADMIN]: 'write',
    [USER_ROLES.DIRECTOR]: 'write',
    [USER_ROLES.MANAGER]: 'write',
    [USER_ROLES.ENGINEER]: 'write', // 工程师可以更新完成度
    [USER_ROLES.BUSINESS]: 'read',
    [USER_ROLES.REGULAR]: 'read'
  },
  
  // 日期字段
  startDate: {
    [USER_ROLES.ADMIN]: 'write',
    [USER_ROLES.DIRECTOR]: 'write',
    [USER_ROLES.MANAGER]: 'write',
    [USER_ROLES.ENGINEER]: 'read',
    [USER_ROLES.BUSINESS]: 'write', // 业务人员可设置日期
    [USER_ROLES.REGULAR]: 'read'
  },
  deadline: {
    [USER_ROLES.ADMIN]: 'write',
    [USER_ROLES.DIRECTOR]: 'write',
    [USER_ROLES.MANAGER]: 'write',
    [USER_ROLES.ENGINEER]: 'read',
    [USER_ROLES.BUSINESS]: 'write', // 业务人员可设置日期
    [USER_ROLES.REGULAR]: 'read'
  },
  
  // 负责人字段
  developmentManager: {
    [USER_ROLES.ADMIN]: 'write',
    [USER_ROLES.DIRECTOR]: 'write',
    [USER_ROLES.MANAGER]: 'write',
    [USER_ROLES.ENGINEER]: 'read',
    [USER_ROLES.BUSINESS]: 'read',
    [USER_ROLES.REGULAR]: 'read'
  },
  businessManager: {
    [USER_ROLES.ADMIN]: 'write',
    [USER_ROLES.DIRECTOR]: 'write',
    [USER_ROLES.MANAGER]: 'write',
    [USER_ROLES.ENGINEER]: 'read',
    [USER_ROLES.BUSINESS]: 'write', // 业务人员可设置业务负责人
    [USER_ROLES.REGULAR]: 'read'
  },
  
  // 敏感信息
  '_openid': {
    [USER_ROLES.ADMIN]: 'read',
    [USER_ROLES.DIRECTOR]: 'none',
    [USER_ROLES.MANAGER]: 'none',
    [USER_ROLES.ENGINEER]: 'none',
    [USER_ROLES.BUSINESS]: 'none',
    [USER_ROLES.REGULAR]: 'none'
  }
};

/**
 * 扩展字段权限策略
 * 由于扩展字段无法一一列举，这里按项目类型和字段模式定义权限
 */
const EXT_FIELD_ACCESS_POLICY = {
  // 霍尔项目特有字段
  '霍尔': {
    'controlMode': {
      [USER_ROLES.ADMIN]: 'write',
      [USER_ROLES.DIRECTOR]: 'write',
      [USER_ROLES.MANAGER]: 'write',
      [USER_ROLES.ENGINEER]: 'write', // 工程师可以设置控制模式
      [USER_ROLES.BUSINESS]: 'read',
      [USER_ROLES.REGULAR]: 'read'
    },
    'controlAlgorithm': {
      [USER_ROLES.ADMIN]: 'write',
      [USER_ROLES.DIRECTOR]: 'write',
      [USER_ROLES.MANAGER]: 'write',
      [USER_ROLES.ENGINEER]: 'write', // 工程师可以设置控制算法
      [USER_ROLES.BUSINESS]: 'read',
      [USER_ROLES.REGULAR]: 'read'
    },
    // 默认规则适用于其他字段
    '*': {
      [USER_ROLES.ADMIN]: 'write',
      [USER_ROLES.DIRECTOR]: 'write',
      [USER_ROLES.MANAGER]: 'write',
      [USER_ROLES.ENGINEER]: 'write',
      [USER_ROLES.BUSINESS]: 'read',
      [USER_ROLES.REGULAR]: 'read'
    }
  },
  
  // 风机项目特有字段
  '风机': {
    '*': {
      [USER_ROLES.ADMIN]: 'write',
      [USER_ROLES.DIRECTOR]: 'write',
      [USER_ROLES.MANAGER]: 'write',
      [USER_ROLES.ENGINEER]: 'write',
      [USER_ROLES.BUSINESS]: 'read',
      [USER_ROLES.REGULAR]: 'read'
    }
  },
  
  // 全局规则，适用于没有特殊定义的扩展字段
  '*': {
    '*': {
      [USER_ROLES.ADMIN]: 'write',
      [USER_ROLES.DIRECTOR]: 'write',
      [USER_ROLES.MANAGER]: 'write',
      [USER_ROLES.ENGINEER]: 'read',
      [USER_ROLES.BUSINESS]: 'read',
      [USER_ROLES.REGULAR]: 'read'
    }
  }
};

/**
 * 初始化角色上下文，用于存储当前请求的角色信息
 */
const roleContext = { currentRole: USER_ROLES.REGULAR };

/**
 * 设置当前角色
 * @param {string} role 角色名称
 */
function setCurrentRole(role) {
  if (Object.values(USER_ROLES).includes(role)) {
    roleContext.currentRole = role;
    return true;
  }
  return false;
}

/**
 * 获取当前角色
 * @returns {string} 角色名称
 */
function getCurrentRole() {
  return roleContext.currentRole;
}

/**
 * 检查字段读取权限
 * @param {string} fieldName 字段名
 * @param {string} role 角色名
 * @param {string} projectType 项目类型（用于扩展字段）
 * @returns {boolean} 是否有权限
 */
function canReadField(fieldName, role = null, projectType = null) {
  const userRole = role || roleContext.currentRole;
  
  // 处理扩展字段权限
  if (fieldName.startsWith('extData.')) {
    const extFieldName = fieldName.replace('extData.', '');
    return canReadExtField(extFieldName, userRole, projectType);
  }
  
  // 处理核心字段权限
  const fieldPolicy = FIELD_ACCESS_POLICY[fieldName];
  
  // 如果没有为该字段定义明确的权限策略，应用默认规则
  if (!fieldPolicy) {
    return userRole !== USER_ROLES.REGULAR; // 默认非普通用户可读
  }
  
  const permission = fieldPolicy[userRole];
  return permission === 'read' || permission === 'write';
}

/**
 * 检查字段写入权限
 * @param {string} fieldName 字段名
 * @param {string} role 角色名
 * @param {string} projectType 项目类型（用于扩展字段）
 * @returns {boolean} 是否有权限
 */
function canWriteField(fieldName, role = null, projectType = null) {
  const userRole = role || roleContext.currentRole;
  
  // 处理扩展字段权限
  if (fieldName.startsWith('extData.')) {
    const extFieldName = fieldName.replace('extData.', '');
    return canWriteExtField(extFieldName, userRole, projectType);
  }
  
  // 处理核心字段权限
  const fieldPolicy = FIELD_ACCESS_POLICY[fieldName];
  
  // 如果没有为该字段定义明确的权限策略，应用默认规则
  if (!fieldPolicy) {
    // 默认只有admin、director、manager可写
    return [USER_ROLES.ADMIN, USER_ROLES.DIRECTOR, USER_ROLES.MANAGER].includes(userRole);
  }
  
  const permission = fieldPolicy[userRole];
  return permission === 'write';
}

/**
 * 检查扩展字段读取权限
 * @param {string} fieldName 扩展字段名
 * @param {string} role 角色名
 * @param {string} projectType 项目类型
 * @returns {boolean} 是否有权限
 */
function canReadExtField(fieldName, role, projectType) {
  const userRole = role || roleContext.currentRole;
  
  // 查找项目类型特有的字段权限
  if (projectType && EXT_FIELD_ACCESS_POLICY[projectType]) {
    // 检查特定字段权限
    if (EXT_FIELD_ACCESS_POLICY[projectType][fieldName]) {
      const permission = EXT_FIELD_ACCESS_POLICY[projectType][fieldName][userRole];
      return permission === 'read' || permission === 'write';
    }
    
    // 检查通配符权限
    if (EXT_FIELD_ACCESS_POLICY[projectType]['*']) {
      const permission = EXT_FIELD_ACCESS_POLICY[projectType]['*'][userRole];
      return permission === 'read' || permission === 'write';
    }
  }
  
  // 应用全局默认规则
  if (EXT_FIELD_ACCESS_POLICY['*'] && EXT_FIELD_ACCESS_POLICY['*']['*']) {
    const permission = EXT_FIELD_ACCESS_POLICY['*']['*'][userRole];
    return permission === 'read' || permission === 'write';
  }
  
  // 最终默认规则
  return [USER_ROLES.ADMIN, USER_ROLES.DIRECTOR, USER_ROLES.MANAGER].includes(userRole);
}

/**
 * 检查扩展字段写入权限
 * @param {string} fieldName 扩展字段名
 * @param {string} role 角色名
 * @param {string} projectType 项目类型
 * @returns {boolean} 是否有权限
 */
function canWriteExtField(fieldName, role, projectType) {
  const userRole = role || roleContext.currentRole;
  
  // 查找项目类型特有的字段权限
  if (projectType && EXT_FIELD_ACCESS_POLICY[projectType]) {
    // 检查特定字段权限
    if (EXT_FIELD_ACCESS_POLICY[projectType][fieldName]) {
      const permission = EXT_FIELD_ACCESS_POLICY[projectType][fieldName][userRole];
      return permission === 'write';
    }
    
    // 检查通配符权限
    if (EXT_FIELD_ACCESS_POLICY[projectType]['*']) {
      const permission = EXT_FIELD_ACCESS_POLICY[projectType]['*'][userRole];
      return permission === 'write';
    }
  }
  
  // 应用全局默认规则
  if (EXT_FIELD_ACCESS_POLICY['*'] && EXT_FIELD_ACCESS_POLICY['*']['*']) {
    const permission = EXT_FIELD_ACCESS_POLICY['*']['*'][userRole];
    return permission === 'write';
  }
  
  // 最终默认规则
  return [USER_ROLES.ADMIN, USER_ROLES.DIRECTOR, USER_ROLES.MANAGER].includes(userRole);
}

/**
 * 过滤对象中的字段，只保留有权限的字段
 * @param {Object} data 数据对象
 * @param {string} accessType 权限类型：'read'或'write'
 * @param {string} role 角色
 * @param {string} projectType 项目类型
 * @returns {Object} 过滤后的数据
 */
function filterFields(data, accessType = 'read', role = null, projectType = null) {
  if (!data) return {};
  
  const result = {};
  const checkFunction = accessType === 'write' ? canWriteField : canReadField;
  
  // 处理核心字段
  for (const key in data) {
    if (key === 'extData') continue; // 单独处理扩展字段
    
    if (checkFunction(key, role, projectType)) {
      result[key] = data[key];
    }
  }
  
  // 处理扩展字段
  if (data.extData && typeof data.extData === 'object') {
    result.extData = {};
    
    for (const key in data.extData) {
      const extFieldName = `extData.${key}`;
      
      if (checkFunction(extFieldName, role, projectType)) {
        result.extData[key] = data.extData[key];
      }
    }
    
    // 如果extData为空对象，则删除它
    if (Object.keys(result.extData).length === 0) {
      delete result.extData;
    }
  }
  
  return result;
}

module.exports = {
  USER_ROLES,
  setCurrentRole,
  getCurrentRole,
  canReadField,
  canWriteField,
  filterFields
}; 